package cn.kgc.vue.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.kgc.vue.commons.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author 课工场
 * @date 2023/12/2
 * @description
 */
@RestController
@RequestMapping("captcha")
@CrossOrigin     // 该接口允许跨域访问
@Api(tags = "验证码模块")
public class CaptchaController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping
    @ApiOperation("获取验证码")
    public ResponseResult getCaptcha() {

        // 生成验证码
        LineCaptcha lineCaptcha = new LineCaptcha(110, 50, 4, 3);
        String code = lineCaptcha.getCode();
        // 存储 redis  k:v   uuid:code
        String simpleUUID = IdUtil.simpleUUID();
        // 将验证码存储在redis中  3min有效
        stringRedisTemplate.opsForValue().set(simpleUUID, code, 3, TimeUnit.MINUTES);

        // 将验证码以base64格式响应给前端    异步请求     simpleUUID
        String imageBase64 = lineCaptcha.getImageBase64();

        HashMap<String, Object> data = new HashMap<>();
        data.put("uuid", simpleUUID);
        data.put("base64Img", imageBase64);
        return ResponseResult.success().data(data);
    }
}
